package com.itqf.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.Scanner;

/**
 * projectName: rbac2103
 *
 * @author: 赵伟风
 * time: 2021/7/9 11:22
 * description:
 */
public class AuthorizationDemo {


//    @CheckRole("jiangshi")
//    @GetMapping("list")
//    public String list(){
//
//
//        return "class/list";
//    }


    public static void main(String[] args) {

        //1.创建securityManagerFactory
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        //2.创建SecurityManager
        SecurityManager securityManager = factory.getInstance();
        //3.引出SecurityManagerUtils
        SecurityUtils.setSecurityManager(securityManager);
        //4.收集账号和密码信息
        Subject subject = SecurityUtils.getSubject();
        //5.认证

        Scanner scanner = new Scanner(System.in);
        System.out.println("请您输入输入账号!");
        String account = scanner.nextLine();
        System.out.println("请您输入输入密码!");
        String password = scanner.nextLine();

        UsernamePasswordToken token = new UsernamePasswordToken(account,password);

        try {

            boolean authenticated = subject.isAuthenticated();
            System.out.println("认证前:authenticated = " + authenticated);


            subject.login(token);
            System.out.println("认证成功");
        }catch (AuthenticationException e)
        {
            System.out.println("认证失败!");
        }

        boolean authenticated = subject.isAuthenticated();
        System.out.println("认证后:authenticated = " + authenticated);




        //只有认证通过才可以获取对应的账号信息!
        //获取用户数据 放入session
        Object principal = subject.getPrincipal();
        System.out.println("principal = " + principal);

        //6.授权
        //检查有没有角色
        boolean is =  subject.isPermitted("class:list"); //boolean
        System.out.println( is);

        is =  subject.isPermitted("class:job"); //boolean
        System.out.println( is);
        //subject.checkRole(); // void

        //检查有没有权限
        boolean anpai = subject.isPermitted("admin:course");
        System.out.println("anpai = " + anpai);
        //subject.checkPermission();


        //7.取消认证
        subject.logout();
    }


}
